<template>
  <view
    :style="{
      display: status ? 'block' : 'none',
      opacity: status ? 1 : 0,
      zIndex: status ? 9 : -1,
    }"
    class="g-shadow"
    @click.stop="globalTouth"
    @touchstart.stop="globalTouth"
  >
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { onUnload } from "@dcloudio/uni-app";
const shadowTimer = ref<any>(null); // 定时器
const shadowTime = ref<any>(0); // 定时器时间
const status = ref<any>(false); // 熄屏状态
const time = ref<any>(30 * 60); // 熄屏时间

onMounted(() => {
  shadowTime.value = time.value;
  setTimer();
});

// 触发全局触摸事件
const globalTouth = () => {
  if (shadowTimer.value) {
    clearTimeout(shadowTimer.value);
  }
  status.value = false;
  shadowTime.value = time.value;
  setTimer();
};

// 设置定时器
const setTimer = () => {
  shadowTimer.value = setTimeout(() => {
    shadowTime.value--;
    if (shadowTime.value <= 0) {
      clearTimeout(shadowTimer.value);
      status.value = true;
      console.log("熄屏");
    } else {
      setTimer();
    }
  }, 1000);
};

onUnload(() => {
  if (shadowTimer.value) {
    clearTimeout(shadowTimer.value);
    shadowTimer.value = null;
    status.value = false;
    shadowTime.value = time.value;
  }
});
defineExpose({
  globalTouth,
});
</script>

<style scoped>
.g-shadow {
  position: fixed;
  display: none;
  opacity: 0;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.9);
  transition: all 0.5s;
}
</style>
